#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>

class ManagedThread
{
public:
    ManagedThread()
    : isRunning_(false)
    , shouldStop_(false)
    {
    }

    void start()
    {
        if(!isRunning_) {
            isRunning_  = true;
            shouldStop_ = false;
            thread_     = std::thread(&ManagedThread::threadFunction, this);
        }
    }

    void pause()
    {
        if(isRunning_) {
            isRunning_ = false;
            cv_.notify_one();  // 唤醒线程以使其暂停
        }
    }

    void resume()
    {
        if(!isRunning_) {
            isRunning_ = true;
            {
                std::lock_guard<std::mutex> lock(mutex_);
                shouldStop_ = false;
            }
            cv_.notify_one();  // 唤醒线程以使其继续执行
        }
    }

    void stop()
    {
        if(isRunning_) {
            isRunning_ = false;
            {
                std::lock_guard<std::mutex> lock(mutex_);
                shouldStop_ = true;
            }
            cv_.notify_one();  // 唤醒线程以使其停止
            if(thread_.joinable()) {
                thread_.join();
            }
        }
    }

private:
    std::thread             thread_;
    std::mutex              mutex_;
    std::condition_variable cv_;
    bool                    isRunning_;
    bool                    shouldStop_;

    void threadFunction()
    {
        while(true) {
            std::unique_lock<std::mutex> lock(mutex_);
            cv_.wait(lock, [this] { return isRunning_ || shouldStop_; });

            if(shouldStop_) {
                break;  // 线程终止
            }

            // 在这里添加线程执行的逻辑
            std::cout << "Thread is running..." << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
};
